<style lang="less" scoped>
@import "./article.less";
</style>
<template>
    <Card>
        <Row :gutter="16" style="margin:15px 0">
            <Button @click="alertAdd" type="primary" icon="plus-round">添加烦租圈</Button>
        </Row>
        <Row :gutter="16">
            <Col>
                <div>
                  <Table :columns="columns" :data="tableData"></Table>
                </div>
                <div class="margin-top-15" style="text-align: center">
                        <Page :total="tableShow.count" :current="tableShow.page" :page-size="tableShow.size" @on-change="changePage" @on-page-size-change="changeSize" show-elevator show-sizer show-total></Page>
                </div>
            </Col>
        </Row>
        <Modal v-model="modalSetting.show" width="668" :styles="{top: '30px'}" :scrollable=true>
          <Form :model="formItem" :label-width="120">
            <!-- <FormItem prop="user" label="发布名称">
                 <Input v-model="formItem.name" placeholder=""></Input>
            </FormItem> -->
            <!-- <FormItem label="用户头像" prop="avatar">
                <Upload
                    action = "https://api.fanzu.vip/api/v1/upload"
                    :show-upload-list = "false"
                    type ="drag"
                    :format = "['jpg','jpeg','png']"
                    :on-success = "success">
                    <template v-if="this.formItem.avatar !== ''">
                      <div style="width: 58px;height:58px;line-height: 58px;">
                        <img :src="this.formItem.avatar" style="height:100%">
                      </div>
                    </template>
                    <template v-else>
                        <div style="width: 58px;height:58px;line-height: 58px;">
                            <Icon type="camera" size="20"></Icon>
                        </div>
                    </template>
                </Upload>
            </FormItem> -->
            <FormItem label="城市" prop="city">
              <al-cascader v-model="formItem.city" level="3" @on-change="selected"/>
            </FormItem>
            <FormItem label="所在详细地址" class="lists" prop="street">
                <Input v-model="formItem.street" @on-change="remoteMethod" @on-focus="changeList(true)" @on-blur="changeList(false)" class="in" placeholder="房屋所在区域街道" style="position:realtive">
                  
                </Input>
                <!-- <ul :v-for="item in streets" style="position:absolute">
                    <li>{{item.address}}</li>
                  </ul> -->
                  <ul class="list" v-bind:class="{ 'showList':listShow }">
                      <li v-for="item in streets" @click="changeItem(item)">
                          {{ item.address }}
                          <span class="append">
                            {{item.district}}
                          </span>
                      </li>
                  </ul>
            </FormItem>
            <FormItem label="选择位置" prop="street">
                <div style="width:100%; height:300px">
                  <el-amap :vid="'amap-vue'" :center="center" :zoom="15" :amap-manager="amapManager" :events="events">
                    <el-amap-marker :position="marker.position" :events="marker.events" :visible="marker.visible" :draggable="true"></el-amap-marker>
                  </el-amap>
                </div>
            </FormItem>
            <FormItem label="内容">
              <Input v-model="formItem.content" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder=""></Input>
            </FormItem>
            <FormItem label="评价图片">
              <div class="demo-upload-list" v-for="item in modelList">
                  <template>
                      <img :src="item.url">
                      <!-- <div class="demo-upload-list-cover">
                          <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                      </div> -->
                  </template>
              </div>
              <Upload
                  ref="upload"
                  :show-upload-list="false"
                  :on-success="handleModelSuccess"
                  :format="['jpg','jpeg','png']"
                  :max-size="2048"
                  :on-format-error="handleFormatError"
                  :on-exceeded-size="handleMaxSize"
                  type="drag"
                  action="https://api.fanzu.vip/api/v1/upload"
                  style="display: inline-block;width:58px;">
                  <div style="width: 58px;height:58px;line-height: 58px;">
                      <Icon type="camera" size="20"></Icon>
                  </div>
              </Upload>
            </FormItem>
            
          </Form>
          <div slot="footer">
            <Button type="primary" @click="submit">提交</Button>
          </div>
        </Modal>
        <Modal v-model="comments.show" width="668" :styles="{top: '30px'}">
          <ul class="comment">
            <template v-for="(item,key) in comments.data">
              <template v-if="item.to==0">
                <li>
                  <span class="cpment">{{item.user.name}}</span>:
                    {{item.content}}
                    <span class="append" >
                      <Icon @click="replay(item,key)" class="plus" type="plus-round"></Icon>
                      <Icon @click="deleteComments(item)" type="close-round" ></Icon>
                    </span>
                    <template v-if="item.replays==true">
                      <Row class="textarea-row">
                        <Input v-model="replayModel.content" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入回复内容"></Input>
                      </Row>
                      <Button class="replay-btn" @click="replaying" style="float:right" type="primary">回复</Button>
                      <div style="clear:both"></div>
                    </template>
                </li>
              </template>
              <template v-else>
                <li>
                  <span class="cpment">{{item.user.name}}</span>
                    回复
                  <span class="cpment">{{item.to.name}}</span>:
                  {{item.content}}
                  <span class="append" >
                    <Icon @click="replay(item,key)" class="plus" type="plus-round"></Icon>
                    <Icon @click="deleteComments(item)" type="close-round"></Icon>
                  </span>
                  <template v-if="item.replays==true">
                    <Row class="textarea-row">
                      <Input v-model="replayModel.content" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入回复内容"></Input>
                    </Row>
                    <Button class="replay-btn" @click="replaying" style="float:right" type="primary">回复</Button>
                    <div style="clear:both"></div>
                  </template>
                </li>
              </template>
            </template>
          </ul>
        </Modal>
    </Card>
</template>

<script>
const statusButton = (vm, h, currentRow, index) => {
  return h(
    "Button",
    {
      props: {
        type: "primary"
      },
      style: {
        margin: "0 5px"
      },
      on: {
        click: () => {
          axios.get("article/" + currentRow.id + "/comments").then(response => {
            let res = response.data
            if (res.code === 200) {
              // this.$Message.success(response.data.msg);
              vm.comments.show = true
              vm.comments.data = res.data.list
              vm.comments.data.forEach(item=>{
                item.replays=false
              })
            } else {
              if (response.data.code === 403) {
                vm.$store.commit("logout", this);
                vm.$router.push({
                  name: "login"
                });
              } else {
                vm.$Message.error(response.data.msg);
              }
            }
          });
        }
      }
    },
    "查看评论"
  );
};
const editButton = (vm, h, currentRow, index) => {
  return h(
    "Button",
    {
      props: {
        type: "primary"
      },
      style: {
        margin: "0 5px"
      }
    },
    "编辑"
  );
};
const deleteButton = (vm, h, currentRow, index) => {
  return h(
    "Button",
    {
      props: {
        type: "error"
      },
      style: {
        margin: "0 5px"
      },
      on:{
        click:()=>{
          axios.delete('article/'+currentRow.id).then(response=>{
            let res = response.data
            if (res.code === 200) {
              vm.$Message.success(response.data.msg);
            } else {
              if (response.data.code === 403) {
                vm.$store.commit("logout", this);
                vm.$router.push({
                  name: "login"
                });
              } else {
                vm.$Message.error(response.data.msg);
              }
            }
            vm.getList();
          })
        }
      }
    },
    "删除"
  );
};
import axios from "axios";
import VueAMap from "vue-amap";
const amapManager = new VueAMap.AMapManager();
export default {
  data() {
    return {
      columns: [
        {
          type: "index",
          title: "序号",
          align: "center"
        },
        {
          title: "用户名",
          align: "center",
          key: "name"
        },
        {
          title: "虚拟发布",
          align: "center",
          key: "virtual"
        },
        {
          title: "内容",
          align: "center",
          key: "content"
        },
        {
          title: "时间",
          align: "center",
          key: "create_time"
        },
        {
          title: "操作",
          align: "center",
          width: 360,
          key: "handle"
        }
      ],
      tableData: [],
      tableShow: {
        page: 1,
        size: 10,
        count: 0
      },
      modalSetting: {
        show: false
      },
      formItem: {
        name: "",
        avatar: "",
        city:[]
      },
      replayModel:{
        article:0,
        to:0,
        content:''
      },
      modelList: [],
      comments:{
        show:false,
        data:[]
      },
      events: {
        init: () => {
          // this.geo = geo
        },
        click: e => {
          this.marker.position = [e.lnglat.lng, e.lnglat.lat];
        }
      },
      marker: {
        position: [121.5273285, 31.21515044],
        events: {
          dragend: e => {
            this.marker.position = [e.lnglat.lng, e.lnglat.lat];
          }
        },
        visible: true
      },
      position: [121.59996, 31.197646],
      center: [121.59996, 31.197646],
      listShow: false,
      streets: [],
      amapManager
    };
  },
  created() {
    this.init();
    this.getList();
  },
  methods: {
    alertAdd() {
      this.modalSetting.show = true;
    },
    init() {
      this.columns.forEach(item => {
        if (item.key === "handle") {
          item.render = (h, params) => {
            return h("div", [
              statusButton(this, h, this.tableData[params.index], params.index),
              // editButton(this, h, this.tableData[params.index], params.index),
              deleteButton(this, h, this.tableData[params.index], params.index)
            ]);
          };
        }
      });
    },
    getList() {
      axios
        .get("article", {
          params: { page: this.tableShow.page, size: this.tableShow.size }
        })
        .then(response => {
          let res = response.data;
          if (res.code === 200) {
            this.tableData = res.data.list;
            this.tableShow.count = res.data.count;
          } else {
            if (response.data.code === 403) {
              this.$store.commit("logout", this);
              this.$router.push({
                name: "login"
              });
            } else {
              this.$Message.error(response.data.msg);
            }
          }
        });
    },
    changePage(page) {
      this.tableShow.page = page;
      this.getList();
    },
    changeSize(size) {
      this.tableShow.size = size;
      this.getList();
    },
    handleModelSuccess(res, file) {
      if (res.code === 200) {
        // file.url = res.data.url;
        // file.name = res.data.name;
        this.modelList.push({ name: res.data.name, url: res.data.url });
      } else {
        this.$Message.error(res.msg);
      }
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: "The file format is incorrect",
        desc:
          "File format of " +
          file.name +
          " is incorrect, please select jpg or png."
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "Exceeding file size limit",
        desc: "File  " + file.name + " is too large, no more than 2M."
      });
    },
    success(res, file) {
      if (res.code === 200) {
        this.formItem.avatar = res.data.url;
      }
    },
    submit() {
      let city =
            this.formItem.city[1].name == "市辖区"
              ? this.formItem.city[0].name
              : this.formItem.city[1].name;
      city = city.replace("市","");
      axios
        .post("article", {
          name: this.formItem.name,
          imgs: this.modelList,
          content: this.formItem.content,
          address: city+"·"+this.formItem.street,
          lng : this.marker.position[0],
          lat : this.marker.position[1]
        })
        .then(response => {
          // this.tableShow.show = false;
          let res = response.data;
          if (res.code === 200) {
            this.$Message.success(response.data.msg);
          } else {
            if (response.data.code === 403) {
              this.$store.commit("logout", this);
              this.$router.push({
                name: "login"
              });
            } else {
              this.$Message.error(response.data.msg);
            }
          }
          this.getList();
          this.modalSetting.show =false
        });
    },
    showComment(id) {
      
    },
    deleteComments(item){
      axios.delete('article/comments/'+item.id).then(response=>{
        let res = response.data
        if(res.code===200){
          this.comments.show = false
          this.$Message.success(response.data.msg)
        }
        else{
          if (response.data.code === 403) {
              this.$store.commit("logout", this);
              this.$router.push({
                name: "login"
              });
            } else {
              this.$Message.error(response.data.msg);
            }
        }
      });
      
    },
    replay(item,index){
      this.comments.data.forEach(item=>{
        if(item.replays==true){
          item.replays = false
        }
      })
      this.replayModel.article = item.article
      this.replayModel.to = item.user.id
      item.replays = true
      this.$set(this.comments.data,index,item)
    },
    replaying(){
      axios.post('article/evaluate',this.replayModel).then(response=>{
        
        let res = response.data
        if(res.code == 200){
          this.$Message.success(res.msg)
        }
        else{
          if (response.data.code === 403) {
              this.$store.commit("logout", this);
              this.$router.push({
                name: "login"
              });
            } else {
              this.$Message.error(response.data.msg);
            }
        }
        this.comments.show = false
      })
    },
    remoteMethod() {
      // console.log(this.formItem.street);

      if (this.formItem.street !== "") {
        this.streetLoading = true;
        let city = "全国";
        let query = this.formItem.street;
        if (this.formItem.city[1] != undefined) {
          city =
            this.formItem.city[1].name == "市辖区"
              ? this.formItem.city[0].name
              : this.formItem.city[1].name;
          query =
            this.formItem.city[0].name +
            city +
            this.formItem.city[2].name +
            this.formItem.street;
        } else {
          this.$Message.error("请选择省市区");
          this.formItem.street = "";
          return;
        }
        let autoComplete = new AMap.Autocomplete({
          city: city
        });
        // let query = this.formItem.city[0].name+city+this.formItem.city[2].name+this.formItem.street
        autoComplete.search(query, (status, result) => {
          if (status === "complete" && result.info === "OK") {
            this.streetLoading = false;
            // this.streets = result.tips;
            this.streets = [];

            result.tips.forEach(item => {
              if (typeof item.address == "string") {
                this.streets.push(item);
                // console.log(item);
              }
            });
            // this.center = [res.lng, res.lat];
          }
        });
      } else {
        this.streets = [];
      }
    },
    changeList(value) {
      if (value == false) {
        setTimeout(() => {
          this.listShow = value;
        }, 150);
      } else this.listShow = value;
    },
    changeItem(item){
      this.formItem.street = item.address
      
      this.marker.position = [item.location.lng,item.location.lat]
      // this.formItem.lat = this.marker.position[1]
      this.center =[item.location.lng,item.location.lat]
    },
    selected(e) {
      let str = "";
      e.forEach(item => {
        str += item.name;
      });

      let geo = new AMap.Geocoder({
        city: "全国"
      });
      geo.getLocation(str, (status, result) => {
        if (status === "complete" && result.info === "OK") {
          let res = result.geocodes[0].location;
          this.center = [res.lng, res.lat];
        }
      });
    },
  }
  
};
</script>